package com.flyme.module.base.provider.service.impl;


import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.entity.SysMessage;
import com.flyme.module.base.client.entity.SysMessageSend;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.mapper.SysMessageMapper;
import com.flyme.module.base.provider.service.SysMessageSendService;
import com.flyme.module.base.provider.service.SysMessageService;
import com.flyme.module.base.provider.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 消息内容接口实现
 *
 * @author flyme
 */
@Slf4j
@Service
@Transactional
public class SysMessageServiceImpl extends BaseServiceImpl<SysMessageMapper, SysMessage> implements SysMessageService {

    @Autowired
    private SysMessageSendService messageSendService;
    @Autowired
    private SysUserService userService;

    @Override
    public List<SysMessage> findByCreateSend(Boolean createSend) {
        return list(q().eq("createSend", createSend));
    }

    @Override
    public void initSysMessage(Long userId) {
        SysUser user = userService.getById(userId);
        List<String> list = messageSendService.selectByUser(userId);
        List<SysMessage> messageList = list(q().notIn(false, "id", list)
            .eq("messageType", 1).eq("sendStatus", 1).ne("sendType", 2));
        if (ObjectUtils.isNotEmpty(messageList)) {
            for (SysMessage sysMessage : messageList) {
                if (sysMessage.getSendType().equals(1) && ObjectUtils.isEmpty(user.getCompanyId())) {
                    continue;
                }
                if (ObjectUtils.isNotNull(userId, sysMessage.getId())) {
                    CriteriaQuery q = new CriteriaQuery<SysMessageSend>();
                    q.eq(true, "userId", userId).eq("messageId", sysMessage.getId());

                    SysMessageSend messageSend = messageSendService.getOne(q,false);
                    if (ObjectUtils.isEmpty(messageSend)) {
                        messageSend = new SysMessageSend();
                        messageSend.setMessageStatus(CommonConstants.DISABLED);
                        messageSend.setMessageId(sysMessage.getId());
                        messageSend.setUserId(userId);
                        messageSend.setMessageType("1");
                        messageSendService.saveOrUpdate(messageSend);
                    }
                }
            }
        }
    }

}